package com.crud.adapter.controller;

import com.crud.application.HBaseService;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/hbase")
public class HBaseController {

    @Autowired
    private HBaseService hBaseService;

    @PostMapping("/createTable")
    public String createTable(@RequestParam String tableName, @RequestParam String[] columnFamilies) {
        try {
            hBaseService.createTable(tableName, columnFamilies);
            return "Table created successfully";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to create table";
        }
    }

    @PostMapping("/insertData")
    public String insertData(@RequestParam String tableName, @RequestParam String rowKey,
                             @RequestParam String columnFamily, @RequestParam String qualifier,
                             @RequestParam String value) {
        try {
            hBaseService.insertData(tableName, rowKey, columnFamily, qualifier, value);
            return "Data inserted successfully";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to insert data";
        }
    }

    @GetMapping("/getData")
    public String getData(@RequestParam String tableName, @RequestParam String rowKey) {
        try {
            Result result = hBaseService.getData(tableName, rowKey);
            return Bytes.toString(result.value());
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to get data";
        }
    }

    @GetMapping("/getAllData")
    public List<Result> getAllData(@RequestParam String tableName) {
        try {
            return hBaseService.getAllData(tableName);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @DeleteMapping("/deleteData")
    public String deleteData(@RequestParam String tableName, @RequestParam String rowKey) {
        try {
            hBaseService.deleteData(tableName, rowKey);
            return "Data deleted successfully";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to delete data";
        }
    }

    @DeleteMapping("/deleteTable")
    public String deleteTable(@RequestParam String tableName) {
        try {
            hBaseService.deleteTable(tableName);
            return "Table deleted successfully";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to delete table";
        }
    }
}
